import Foundation

protocol MPConvertibleSet {
    func mp_to_array() -> [Any]
    
    static func mp_subType() -> Any.Type
}

extension MPConvertibleSet where Self: Sequence {
    func mp_to_array() -> [Any] {
        return map { $0 }
    }
    
    static func mp_subType() -> Any.Type {
        if let optionType = self.Element as? MPConvertibleOptional.Type {
            return optionType.mp_subType()
        }
        return self.Element
    }
}

extension NSSet: MPConvertibleSet {}
extension Set: MPConvertibleSet {}

func mp_set(_ value: Any, type: Any.Type?, subType: Any.Type?) -> MPConvertibleSet? {
    guard let array = value as? [Any] ?? (value as? MPConvertibleSet)?.mp_to_array() else { return nil }
    let list : [Any]
    if let _subType = subType as? MPConvertible.Type {
        list = array.compactMap {
            if let dic = mp_valueToDic($0) {
                return _subType.mp_model(dic)
            }
            return nil
        }
    }else {
        list = array
    }
    return type is NSMutableSet.Type ? NSMutableSet(array: list) : NSSet(array: list)
}
